/*
 *  Copyright (C) 2010 Martin Haulrich <mwh.isv@cbs.dk>
 *
 *  This file is part of the MatrixParser package.
 *
 *  The MatrixParser program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.osdtsystem.matrixparser.features;

import java.util.List;
import java.util.Map.Entry;

/**
 *
 * @author Martin Haulrich
 */
public class FeatureVectorUtils {

    /**
     * Find distance between two feature vectors
     * @param fva
     * @param fvb
     * @return
     */
    public static FeatureVector distance(FeatureVector fva, FeatureVector fvb) {
        FeatureVector distanceVector = new SparseFeatureVector();

        for (Entry<Feature,Double> entry : fva) {
            distanceVector.setValue(entry.getKey(), entry.getValue());
        }
        for (Entry<Feature,Double> entry : fvb) {
            Feature f = entry.getKey();
            Double v = distanceVector.getValue(f);
            distanceVector.setValue(f,
                    v - fvb.getValue(f));
        }
        return distanceVector;
    }

    /**
     * Merge list of feature vectors into one vector
     * @param vectors
     * @return
     */
    public static FeatureVector mergeVectors(List<FeatureVector> vectors) {
        return(FeatureVectorFactory.union(vectors));
        /*FeatureVector mergedVector = new SparseFeatureVector();
        for (FeatureVector fv : vectors) {
        for (Entry<Feature,Double> entry : fv) {
        Feature f = entry.getKey();
        Double v = mergedVector.getValue(f);
        mergedVector.setValue(f,
        mergedVector.getValue(f) + fv.getValue(f));
        
        }
        }return mergedVector;
         */
    }

    /**
     *
     * @param fva
     * @param fvb
     * @return
     */
    public static double dotProduct(FeatureVector fva, FeatureVector fvb) {
        if (fva.size() > fvb.size()) {
            FeatureVector swap = fva;
            fva = fvb;
            fvb = swap;
        }

        double res = 0;
        for (Entry<Feature,Double> entry : fva) {
            res = res + entry.getValue() * fvb.getValue(entry.getKey());
        }
        return res;
    }
}
